package cn.kooki.app.duobao.ui.Activity.Comm;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.google.gson.Gson;
import com.qihoo.appstore.updatelib.UpdateManager;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.update.UmengUpdateAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Bind;
import cn.kooki.app.duobao.BuildConfig;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseActivity;
import cn.kooki.app.duobao.core.ContactService;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.ContactInfo;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.AddShopEvent;
import cn.kooki.app.duobao.data.bus.BonusEvent;
import cn.kooki.app.duobao.data.bus.ChangePageEvent;
import cn.kooki.app.duobao.data.bus.OnRequestEvent;
import cn.kooki.app.duobao.data.bus.WinEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Fragment.CartFragment;
import cn.kooki.app.duobao.ui.Fragment.IndexFragment;
import cn.kooki.app.duobao.ui.Fragment.NewLotteryFragment;
import cn.kooki.app.duobao.ui.Fragment.ShareFragment;
import cn.kooki.app.duobao.ui.Fragment.UserFragment;
import cn.kooki.app.duobao.ui.widget.PushWinDialogUtils;
import cn.kooki.app.duobao.util.NetWorkUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.ShareUtils;
import cn.kooki.app.duobao.util.StatusBarCompat;
import cn.kooki.app.duobao.util.UpdateUtils;
import cn.kooki.app.duobao.util.manager.AppManager;
import cn.kooki.app.duobao.util.manager.CartObserver;
import cn.kooki.app.duobao.util.manager.ContactUtils;
import cn.kooki.app.duobao.util.manager.LoginManager;
import cn.kooki.app.duobao.util.manager.ShopCartManager;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/11/25.
 */
public class RootAcitivity extends BaseActivity implements View.OnClickListener, CartObserver {
    @Bind(R.id.main_view_pager)
    ViewPager mainViewPager;
    @Bind(R.id.tab_icon0)
    ImageView tabIcon0;
    @Bind(R.id.tab_label0)
    TextView tabLabel0;
    @Bind(R.id.tab_wrapper0)
    RelativeLayout tabWrapper0;
    @Bind(R.id.tab_icon1)
    ImageView tabIcon1;
    @Bind(R.id.tab_label1)
    TextView tabLabel1;
    @Bind(R.id.tab_wrapper1)
    RelativeLayout tabWrapper1;
    @Bind(R.id.tab_icon2)
    ImageView tabIcon2;
    @Bind(R.id.tab_label2)
    TextView tabLabel2;
    @Bind(R.id.tab_icon_wrapper2)
    LinearLayout tabIconWrapper2;
    @Bind(R.id.tab_dot2)
    ImageView tabDot2;
    @Bind(R.id.tab_wrapper2)
    RelativeLayout tabWrapper2;
    @Bind(R.id.tab_icon3)
    ImageView tabIcon3;
    @Bind(R.id.tab_label3)
    TextView tabLabel3;
    @Bind(R.id.tab_icon_wrapper3)
    LinearLayout tabIconWrapper3;
    @Bind(R.id.tab_wrapper3)
    RelativeLayout tabWrapper3;
    @Bind(R.id.tab_icon4)
    ImageView tabIcon4;
    @Bind(R.id.tab_label4)
    TextView tabLabel4;
    @Bind(R.id.tab_wrapper4)
    RelativeLayout tabWrapper4;
    @Bind(R.id.tab)
    LinearLayout tab;
    @Bind(R.id.animation_wrapper)
    RelativeLayout animationWrapper;
    @Bind(R.id.cart_tab_badge)
    TextView cartTabBadge;
    private IndexPageAdapter indexPageAdapter;
    private IndexFragment indexFragment;
    private NewLotteryFragment lotteryFragment;
    private ShareFragment shareFragment;
    private CartFragment cartFragment;
    private UserFragment userFragment;
    private ImageView mAnimiImageView;
    private int x;
    private int y;
    private long AnimationDuration = 1000;
    private int cartnumber = 0;
    private boolean isClean = false;
    private int number = 0;
    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //用来清除动画后留下的垃圾
                    try {
                        animationWrapper.removeAllViews();
                        animationWrapper.setVisibility(View.GONE);

                    } catch (Exception e) {

                    }
                    isClean = false;
                    break;
                default:
                    break;
            }
        }
    };
    private int statusBarHeight;
    private LoginManager manager;
    private String content;
    private String url;


    @Override
    protected void setToolbar() {

    }

    @Override
    protected void setLayoutContentView() {
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }


    private void doAnim(AddShopEvent event) {
        if (!isClean) {
            startAddAnimiotr(event);
        } else {
            try {
                animationWrapper.removeAllViews();
                isClean = false;
                startAddAnimiotr(event);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                isClean = true;
            }
        }
    }

    @Override
    protected void afterView() {
        setupViewpager();

        ShopCartManager.getInstance().changeObservable.registerObserver(this);
        Intent intent = new Intent(this, ContactService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, intent, 0);

//AlarmManager对象,注意这里并不是new一个对象，Alarmmanager为系统级服务
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

//设置闹钟从当前时间开始，每隔5s执行一次PendingIntent对象pi，注意第一个参数与第二个参数的关系
// 5秒后通过PendingIntent pi对象发送广播
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() - 3600 * 1000 * 24, 3600 * 1000 * 24, pi);
        if (Constants.AUTO_TYPE_360.equals(BuildConfig.AUTO_TYPE)) {
            UpdateManager.checkUpdate(this);
        } else if (Constants.AUTO_TYPE_BAIDU.equals(BuildConfig.AUTO_TYPE)) {
            BDAutoUpdateSDK.silenceUpdateAction(this);//百度静默更新
        } else {
            UmengUpdateAgent.update(getApplicationContext());
        }

        checkShowPush();

//        LoginManager.checkIsNew(SharePreferencesUtils.getUserinfo(this).getUid());
//        show();
//        PushWinDialogUtils.showFristDilaog(this, true);
//        PushWinDialogUtils.showFristDilaog(this, false);
//        postBonus();
    }


    private void show() {
        new AlertDialog.Builder(this)
                .setView(R.layout.layout_share_bonus)
                .setNegativeButton("分享红包给好友", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showShareDialog();
                    }
                }).setPositiveButton("取消", null).show();
    }


    private void showShareDialog() {
        UserInfo userinfo = SharePreferencesUtils.getUserinfo(this);
        content = "一元收获惊喜，亲测有效！现在我把好运气人品都传给你，快来领取吧！";
        final String title = "朋友夺到宝，分给你了！";
        final UMImage image = new UMImage(this, R.drawable.takeout_ic_coupon_wm);
        ShareUtils shareUtils = new ShareUtils();
        url = Constants.APP_SHARE_URL+userinfo.getUid();
        final String finalTitle = title;
        shareUtils.showShareDialog(this, new ShareUtils.shareItemClickLister() {
            @Override
            public void onClick(SHARE_MEDIA media) {
                if (media == SHARE_MEDIA.SINA) {
                    content = content + url;
                }
                new ShareAction(RootAcitivity.this)
                        .setPlatform(media)
                        .withTitle(finalTitle).withMedia(image)
                        .withText(content).withTargetUrl(url)
                        .share();
            }
        });
    }

    private void checkShowPush() {
        final int type = getIntent().getIntExtra("type", -1);
        final String title = getIntent().getStringExtra("title");
        final String text = getIntent().getStringExtra("text");
        final String username = getIntent().getStringExtra("username");
        if (type == 0) {
            WinEvent winEvent = new WinEvent();
            winEvent.goodname = title;
            winEvent.uname = username;
            PushWinDialogUtils.showDilaog(this, winEvent);
        } else if (type == 1) {
            BonusEvent bonusEvent = new BonusEvent();
            bonusEvent.title = text;
            PushWinDialogUtils.showBonusDiaog(this, bonusEvent);
        }
    }


    private void getIsOne() {
        MainFactory.getApiInstance().IsOneBonus("161930", 2, new Callback<BaseResponse>() {
            @Override
            public void success(BaseResponse baseResponse, Response response) {
                if (baseResponse.getStatus() == 0) {
                    PushWinDialogUtils.showFristDilaog(RootAcitivity.this, true);
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }


    private void checkupload() {
        final UserInfo userinfo = SharePreferencesUtils.getUserinfo(getApplication());
        boolean islogin = SharePreferencesUtils.getBoolean(getApplication(), SharePreferencesUtils.ISLOGIN);
        if (!TextUtils.isEmpty(userinfo.getUid()) && islogin && NetWorkUtils.isWifiConnected(getApplication())) {
            ContactUtils.getContacts(getApplication(), new ContactUtils.ContactCallback() {
                @Override
                public void onQueryCompelete(ArrayList<ContactInfo> infos) {
                    Log.i("contact", "upload");
                    if (infos.size() > 0) {
                        Gson gson = new Gson();
                        String json = gson.toJson(infos);
                        MainFactory.getApiInstance().uploadContacts(userinfo.getUid(), json, new Callback<BaseResponse>() {
                            @Override
                            public void success(BaseResponse baseResponse, Response response) {

                            }

                            @Override
                            public void failure(RetrofitError error) {

                            }
                        });
                    }
                }
            });
        }
    }

    /**
     * 测试
     */
    private void postBonus() {
        new AlertDialog.Builder(this)
                .setView(R.layout.layout_share_bonus)
                .setNegativeButton("分享红包给好友", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        showShareDialog();
                    }
                }).setPositiveButton("取消", null).show();
    }


    private void setupViewpager() {

        StatusBarCompat.compat(this, getResources().getColor(R.color.main_red_dark));
        indexPageAdapter = new IndexPageAdapter(getSupportFragmentManager());
        indexFragment = new IndexFragment();
        lotteryFragment = new NewLotteryFragment();
        shareFragment = new ShareFragment();
        cartFragment = new CartFragment();
        userFragment = new UserFragment();


        indexPageAdapter.addFragment(indexFragment);
        indexPageAdapter.addFragment(lotteryFragment);
        indexPageAdapter.addFragment(shareFragment);
        indexPageAdapter.addFragment(cartFragment);
        indexPageAdapter.addFragment(userFragment);
        mainViewPager.setAdapter(indexPageAdapter);
        mainViewPager.setOffscreenPageLimit(5);
        mainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                changebottombar(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabWrapper0.setOnClickListener(this);
        tabWrapper1.setOnClickListener(this);
        tabWrapper2.setOnClickListener(this);
        tabWrapper3.setOnClickListener(this);
        tabWrapper4.setOnClickListener(this);
        tabWrapper0.setSelected(true);

    }

    private void changebottombar(int position) {
        tabWrapper0.setSelected(false);
        tabWrapper1.setSelected(false);
        tabWrapper2.setSelected(false);
        tabWrapper3.setSelected(false);
        tabWrapper4.setSelected(false);
        switch (position) {
            case 0:
                StatusBarCompat.compat(this, getResources().getColor(R.color.main_red_dark));
                tabWrapper0.setSelected(true);
                break;
            case 1:
                tabWrapper1.setSelected(true);
                StatusBarCompat.compat(this, getResources().getColor(android.support.v7.appcompat.R.color.material_grey_600));
                break;
            case 2:
                tabWrapper2.setSelected(true);
                StatusBarCompat.compat(this, getResources().getColor(android.support.v7.appcompat.R.color.material_grey_600));
                break;
            case 3:
                StatusBarCompat.compat(this, getResources().getColor(android.support.v7.appcompat.R.color.material_grey_600));
                tabWrapper3.setSelected(true);
                break;
            case 4:
                if (SharePreferencesUtils.getBoolean(this, SharePreferencesUtils.ISLOGIN)) {
                    StatusBarCompat.compat(this, getResources().getColor(R.color.main_red_dark));
                } else {
                    StatusBarCompat.compat(this, getResources().getColor(android.support.v7.appcompat.R.color.material_grey_600));
                }
                tabWrapper4.setSelected(true);
                break;
        }
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (statusBarHeight == 0) {
            Rect frame = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            statusBarHeight = frame.top;
        }
    }


    public void onEventMainThread(AddShopEvent event) {
        doAnim(event);
    }

    public void onEventMainThread(ChangePageEvent event) {

        if (mainViewPager != null) {
            mainViewPager.setCurrentItem(event.item, event.animation);
        }
    }

    public void startAddAnimiotr(final AddShopEvent event) {
        animationWrapper.setVisibility(View.VISIBLE);

        final ImageView mAnimiImageView = new ImageView(this);
        mAnimiImageView.setLayoutParams(event.layoutParams);
        animationWrapper.addView(mAnimiImageView);
        mAnimiImageView.setImageDrawable(event.drawable);
        int fromx = event.loaction[0];
        int fromy = event.loaction[1];
        mAnimiImageView.setX(fromx);
        mAnimiImageView.setY(fromy - statusBarHeight);
        mAnimiImageView.setVisibility(View.VISIBLE);
        int[] end_location = new int[2];
        tabWrapper3.getLocationInWindow(end_location);
        int endX = end_location[0];
        int endY = end_location[1] - statusBarHeight;

        mAnimiImageView.animate().alpha(0.0f).setDuration(AnimationDuration).
                translationX(endX).scaleX(0.4f).scaleY(0.4f).translationY(endY).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                number--;
                mAnimiImageView.setVisibility(View.GONE);
                ShopCartManager.getInstance().addShopCart(event.item);

                if (number == 0) {
                    isClean = true;
                    myHandler.sendEmptyMessage(0);
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                number++;
            }
        }).start();

    }


    @Override
    public void onBackPressed() {
        if (mainViewPager.getCurrentItem() != 0) {
            mainViewPager.setCurrentItem(0);
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        if (v == tabWrapper0 || v == tabWrapper1 || v == tabWrapper2 || v == tabWrapper3 || v == tabWrapper4) {
            String index = (String) v.getTag();
            changebottombar(Integer.parseInt(index));
            mainViewPager.setCurrentItem(Integer.parseInt(index));
        }
    }


    @Override
    public void onChanged(int count) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShopCartManager.getInstance().changeObservable.unregisterObserver(this);
        myHandler = null;

    }

    @Override
    public void onCheckedChange(int count, boolean isCancelEditing) {

    }

    @Override
    public void onCartsChange() {
        int cartsSize = ShopCartManager.getInstance().getCartsSize();
        if (cartsSize > 0) {
            cartTabBadge.setText(cartsSize + "");
            cartTabBadge.setVisibility(View.VISIBLE);
        } else {
            cartTabBadge.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    static class IndexPageAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragments = new ArrayList<>();

        public IndexPageAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment) {
            fragments.add(fragment);
        }

        public void remove(Fragment fragment) {
            fragments.remove(fragment);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }
}
